<script setup lang="ts">
import { ref } from 'vue';
import { useNurseUser, use_hospital_dept_bed } from '@/service';
import { useGetAuthInfo, useImage } from '@/hooks';
import Taro, {
    hideLoading,
    showLoading,
    usePullDownRefresh,
    stopPullDownRefresh,
    showToast,
    navigateBack
} from '@tarojs/taro';
import { SUCCESS_MSG_DURATION } from '@/constants';
import { storeToRefs } from 'pinia';
import { useAuthStore } from '@/store';
import { calculateDistance } from '@/utils';
import { localStg } from '@/utils/storage';

definePageConfig({
    navigationBarTitleText: '选择医疗机构'
    // enablePullDownRefresh: true //下拉刷新
});

const { editDefaultHospital } = useNurseUser();

const { getHospitalListByArea } = use_hospital_dept_bed();

const { nurseUser, currentCity } = storeToRefs(useAuthStore());

const data: any = ref([]);

const data_old: any = ref([]);

const searchValue = ref('');

const latitude = ref(-999);

const longitude = ref(-999);

getLocation();
getData();

// 下拉刷新
usePullDownRefresh(() => {
    getData();
    stopPullDownRefresh();
});

// 获取数据
async function getData() {
    showLoading({ title: '正在请求数据...' });

    const { error, success } = await getHospitalListByArea(currentCity.value);
    if (!error && success) {
        data.value = success;
        data_old.value = success;
    }

    hideLoading();
}

// 切换机构
async function switchAgency(defaultHospital: any, defaultHospitalName: any, item:any) {
    showLoading({ title: '正在切换机构...' });
    console.log("item", item, "nurseUser.value.openid", nurseUser.value.openid);
    
    // 存储 sysOrgCode 到 localStorage
    if (item.sysOrgCode) {
        localStg.set('sys_org_code', item.sysOrgCode);
    }
    
    if (nurseUser.value.openid) {
        const { error } = await editDefaultHospital({ userId: nurseUser.value.id, defaultHospital, defaultHospitalName });
        if (!error) {
            useGetAuthInfo();
        }
    } else {
        nurseUser.value.defaultHospital = defaultHospital;
        nurseUser.value.defaultHospitalName = defaultHospitalName;

    }
    nurseUser.value.distance = item.distance;
    // nurseUser.value.defaultHospitalName = item.latitude;
    nurseUser.value.defaultHospitalLatitude = item.latitude;
    nurseUser.value.defaultHospitalLongitude = item.longitude
    hideLoading();
    showToast({
        title: '切换成功',
        icon: 'success',
        duration: SUCCESS_MSG_DURATION
    });
    const pages = Taro.getCurrentPages();
    const current = pages[pages.length - 1]; /* 从堆栈中获取当前界面的属性 */
    const eventChannel = current.getOpenerEventChannel();
    eventChannel.emit('switchNearShop', {
        data: { defaultHospitalName, distance: item.distance}
    });
    setTimeout(() => {
        navigateBack();
    }, 1200);
}

// 搜索机构
function searchAgency() {
    if (!searchValue.value) searchValue.value = '';
    data.value = data_old.value;
    data.value = data.value.filter((item: any) => item.name.includes(searchValue.value));
}

// 切换城市
function switchCity() {
    Taro.navigateTo({
        url: '/package/switchcity/index',
        events: {
            switchCity(data: any) {
                getData(); // 切换城市后刷新机构
                stopPullDownRefresh();
            }
        }
    });
}

// 获取用户当前位置
function getLocation() {
    try {
        Taro.getLocation({
            type: 'wgs84',
            // type: 'gcj02',
            needFullAccuracy: true,
            success(res) {
                latitude.value = res.latitude;
                longitude.value = res.longitude;
            }
        });
    } catch (err) {
        Taro.showModal({
            title: '提示',
            content: '获取位置服务信息失败!',
            showCancel: false,
            success(res) {
                if (res.confirm) {
                    // console.log('用户点击确定')
                } else if (res.cancel) {
                    // console.log('用户点击取消')
                }
            }
        });
    }
}
</script>

<template>
    <basic-layout>
        <!-- <custom-navbar title="选择医疗机构" showLeft/> -->
        <view class="w-375px text-primary flex-col-center justify-start m-b-20">
            <view class="w-full text-gray">
                <nut-searchbar v-model="searchValue" placeholder="搜索医疗机构" @search="searchAgency()">
                    <template #leftout>
                        <span class="text-base text-gray" @click="switchCity()">
                            {{ currentCity }}
                        </span>
                        <view class="i-local-drop-down w-16px h-16px" @click="switchCity()"></view>
                    </template>
                    <template #rightout>
                        <nut-button type="default" size="small" @click="searchAgency()">搜索</nut-button>
                    </template>
                </nut-searchbar>
            </view>
            <nut-empty v-if="data?.length == 0" description="暂无数据"></nut-empty>
            <view v-for="item in data" class="w-360px">
                <view class="bg-#fff b-rounded-3 shadow flex h-75px mt-2 flex-col justify-around items-start"
                    @click="switchAgency(item.id, item.name, item)">
                    <view class="flex-center w-full h-full">
                        <view class="w-full h-full flex justify-start items-center">
                            <view class="ml-2">
                                <nut-avatar size="large"><img :src="useImage(item.logo)" /></nut-avatar>
                            </view>
                            <view class="ml-2 flex-col-center items-start">
                                <view class="flex justify-between items-center">
                                    <view class="mr-2 font-bold">{{ item.name }}</view>
                                </view>
                                <view class="flex-center text-sm mt-2 text-gray">
                                    <view class="i-local-location w-14px h-14px" />
                                    <view class="w-180px">
                                        <nut-ellipsis direction="end" :content="item.address" />
                                    </view>
                                    <text v-if="latitude != -999" class="ml-4">
                                        {{ item.distance = calculateDistance(latitude, longitude, item.latitude, item.longitude, 2) +
                                        'km' }}
                                    </text>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
    </basic-layout>
</template>
